﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Media.Imaging;

namespace LyalinSamples.WP7Client.MaVHubInt
{
    public class UCToBitmapHelper
    {
        private static UserControl RenderImageToSize(UserControl uc, int Width, int Height)
        {
            // Force UserControl to render to a certain size
            uc.Width = Width;
            uc.Height = Height;
            uc.Measure(new Size(Width, Height));
            uc.Arrange(new Rect(0, 0, Width, Height));

            return uc;
        }

        public static Stream WriteableBitmapFromUserControl(UserControl uc, int Width, int Height, int Quality)
        {
            Stream outputStream = new MemoryStream();

            // Write to Bitmpa and save to Memory Stream
            WriteableBitmap WriteableBitmapImage = new WriteableBitmap(RenderImageToSize(uc, Width, Height), null);

            WriteableBitmapImage.SaveJpeg(outputStream, (int)uc.ActualWidth, (int)uc.ActualHeight, 0, Quality);

            // Reset position to zero or Music and Video hub will kick "partial read" exception
            outputStream.Position = 0;

            return outputStream;
        }
    }
}
